package com.dl698.asn1.axdr;

import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

import java.io.IOException;

/**
 * AXDR布尔类型
 * 实现布尔值的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrBoolean implements AxdrType {

    private boolean val = false;
    private byte[] dataCode = null;

    /**
     * 默认构造函数
     */
    public AxdrBoolean() {
    }

    /**
     * 构造函数
     * 
     * @param val 布尔值
     */
    public AxdrBoolean(boolean val) {
        this.val = val;
    }

    /**
     * 设置值
     * 
     * @param val 布尔值
     */
    public void setVal(boolean val) {
        this.val = val;
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 编码数据
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        try {
            if (dataCode != null) {
                output.writeByte(dataCode);
            } else if (val) {
                output.write(0x01);
            } else {
                output.write(0x00);
            }
            return 1;
        } catch (IOException e) {
            throw new RuntimeException("Encode error", e);
        }
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        if (input.available() == 0) {
            return 0;
        }
        val = input.read() != 0x00;
        return 1;
    }

    /**
     * 获取值
     * 
     * @return 布尔值
     */
    public boolean getVal() {
        return val;
    }

    /**
     * 获取数据编码
     * 
     * @return 数据编码
     */
    public byte[] getDataCode() {
        return dataCode;
    }

    @Override
    public String toString() {
        return String.valueOf(val);
    }
}